import { decodeJwt } from 'jose'
import { defineStore } from 'pinia'

import type { UserInfoRes, UserRole } from '@/api/model/user'
import { getUserInfo as queryUserInfo, login } from '@/api/user'
import { usePermissionStore } from '@/store'

interface StoreUserInfo {
  id: string
  name: string
  roles: Array<UserRole>
}

const InitUserInfo: StoreUserInfo = {
  id: '',
  name: '', // 用户名，用于展示在页面右上角头像处
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '', // 默认token不走权限
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles
    },
  },
  actions: {
    async login(username: string, password: string) {
      const res = await login(username, password)
      this.token = res.token
      const payload = decodeJwt<{ userData: UserInfoRes }>(res.token)
      this.userInfo = {
        id: payload.userData.id,
        name: payload.userData.userName,
        roles: [payload.userData.userRole],
      }
      const permissionStore = usePermissionStore()
      await permissionStore.initRoutes(this.roles)
    },
    async getUserInfo() {
      const ueserInfo = await queryUserInfo()
      this.userInfo = {
        id: ueserInfo.id,
        name: ueserInfo.userName,
        roles: [ueserInfo.userRole],
      }
      const permissionStore = usePermissionStore()
      await permissionStore.initRoutes(this.roles)
    },
    async logout() {
      this.token = ''
      this.userInfo = { ...InitUserInfo }
    },
  },
  persist: {
    key: 'user',
    pick: ['token', 'userInfo'],
    afterHydrate({ store }) {
      console.log('store', store)
      const permissionStore = usePermissionStore()
      permissionStore.initRoutes(store.roles)
    },
  },
})
